package com.ali.g308_ai.service.impl;

import com.ali.g308_ai.pojo.entity.ChatIdsEntity;
import com.ali.g308_ai.repository.ChatIdsRepository;
import com.ali.g308_ai.service.ChatIdsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
@RequiredArgsConstructor
public class ChatIdsServiceImpl implements ChatIdsService {
    private final ChatIdsRepository chatIdsRepository;

    public void saveChatIds(String type, String chatId) {
        ChatIdsEntity entity = chatIdsRepository.findByType(type);
        if(entity != null) {
            entity.getChatIds().add(chatId);
        } else {
            entity = ChatIdsEntity.builder()
                    .type(type)
                    .chatIds(new HashSet<>(Collections.singleton(chatId)))
                    .build();
        }
        chatIdsRepository.save(entity);
    }

    public List<String> getChatIds(String type) {
        ChatIdsEntity entity = chatIdsRepository.findByType(type);
        return entity == null ? Collections.emptyList() : new ArrayList<>(entity.getChatIds());
    }
}
